import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Course } from './entities/course.entity';
import { CreateCourseDto } from './dto/create-course.dto';
import { UpdateCourseDto } from './dto/update-course.dto';
import { Teacher } from '../teacher/entities/teacher.entity';

@Injectable()
export class CourseService {
  constructor(
    @InjectRepository(Course)
    private readonly courseRepo: Repository<Course>,
    @InjectRepository(Teacher) // 新增注入教师仓库
    private readonly teacherRepo: 
    Repository<Teacher>
  ) {}

  async create(createCourseDto: CreateCourseDto): Promise<Course> {
    // 新增教师查询逻辑
    const teacher = await this.teacherRepo.findOneBy({ 
      tno: createCourseDto.tno 
    });
    
    if (!teacher) {
      throw new NotFoundException(`教师 ${createCourseDto.tno} 不存在`);
    }

    // 创建课程时关联教师
    const course = this.courseRepo.create({
      cname: createCourseDto.cname,
      cdept: createCourseDto.cdept,
      credit: createCourseDto.credit ?? 2,
      teacher: teacher  // 使用关联关系
    });

    return this.courseRepo.save(course);
  }

  async findAll(page: number = 1, pageSize: number = 10): Promise<{
    list: Course[];
    itemCount: number;
    page: number;
    pageSize: number;
    pageCount: number;
  }> {
    const skip = (page - 1) * pageSize;
    const [data, total] = await this.courseRepo.findAndCount({
      skip,
      take: pageSize,
      order: { cno: 'ASC' },
      relations: ['teacher']
    });
  
    return {
      list: data,
      itemCount: total,
      page,
      pageSize,
      pageCount: Math.ceil(total / pageSize)
    };
  }

  async findOne(cno: number): Promise<Course> {
    const course = await this.courseRepo.findOne({
      where: { cno },
      relations: ['teacher']  // 新增关联查询
    });
    
    if (!course) {
      throw new NotFoundException(`Course #${cno} not found`);
    }
    return course;
  }

  async update(cno: number, updateCourseDto: UpdateCourseDto): Promise<Course> {
    const course = await this.courseRepo.preload({
      cno,
      ...updateCourseDto
    });
    
    if (!course) {
      throw new NotFoundException(`Course #${cno} not found`);
    }
    
    return this.courseRepo.save(course);
  }

  async remove(cno: number): Promise<void> {
    const result = await this.courseRepo.delete(cno);
    if (result.affected === 0) {
      throw new NotFoundException(`Course #${cno} not found`);
    }
  }
}
